package org.jdragon.springz.web.core.entity;

import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedFile;
import io.netty.handler.stream.ChunkedStream;
import io.netty.util.AsciiString;
import lombok.SneakyThrows;
import org.jdragon.springz.web.core.factory.FullHttpResponseFactory;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;

/**
 * @Author JDragon
 * @Date 2021.03.02 下午 9:56
 * @Email 1061917196@qq.com
 * @Des:
 */
public class HttpResponse {
    private static final AsciiString CONNECTION = AsciiString.cached("Connection");
    private static final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive");

    private ChannelHandlerContext channelHandlerContext;

    private boolean keepAlive;

    public HttpResponse(ChannelHandlerContext channelHandlerContext, boolean keepAlive) {
        this.channelHandlerContext = channelHandlerContext;
        this.keepAlive = keepAlive;
    }

    @SneakyThrows
    public void write(ResponseData responseData) {
        FullHttpResponse fullHttpResponse = FullHttpResponseFactory.buildSuccessResponse(responseData);
        if (!keepAlive) {
            channelHandlerContext.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
        } else {
            fullHttpResponse.headers().set(CONNECTION, KEEP_ALIVE);
            channelHandlerContext.writeAndFlush(fullHttpResponse);
        }
    }

    public void writerFile(String fileName) {
        this.write(new File(fileName));
    }

    @SneakyThrows
    public void write(File file) {
        this.write(new FileInputStream(file));
    }

    @SneakyThrows
    public void write(InputStream inputStream) {
        io.netty.handler.codec.http.HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        HttpUtil.setContentLength(response, inputStream.available());
        MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType("环境.xlsx"));

        if (keepAlive) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        channelHandlerContext.write(response);
        channelHandlerContext.write(new ChunkedStream(inputStream));
    }

}
